import subprocess
import time

import pandas as pd
import threading
import shlex


class LogcatMonitor:
    CMD = '\'adb logcat DualTest:V *:S -b main\''
    CMD1 = '\'while true; do echo 11-15 00:18:01.844  6511  6778 D DualTest: 0 14.433 14.436; sleep 1; done\''

    def __init__(self):
        self.df_columns = ['Cam-0-sync',
                           'Cam-0-async',
                           'Cam-1-sync',
                           'Cam-1-async']
        self.data = pd.DataFrame(columns=self.df_columns)
        self.thread = threading.Thread(target=self.run, name='LogcatMonitor', args=(self,))
        self.process = None
        self.is_alive = False

    def start(self):
        self.is_alive = True
        self.process = subprocess.Popen(shlex.split(LogcatMonitor.CMD),
                                        bufsize=1,
                                        stdin=subprocess.PIPE,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE,
                                        shell=True)
        self.thread.start()

    def stop(self):
        self.is_alive = False
        self.thread.join()

    def run(self, arg):
        print('Logcat is running...')
        # (stdout, stderr) = arg.process.communicate()
        while self.is_alive:
            line = self.process.stdout.readline().decode('utf-8')
            if len(line) > 0:
                self.parse_line(line)

    def parse_line(self, line):
        elements = line[:-2].split()
        new_row = dict()

        print(elements)
        new_row['Cam-%s-sync' % elements[6]] = elements[7]
        new_row['Cam-%s-async' % elements[6]] = elements[8]
        s = pd.Series(new_row, index=self.df_columns, name=elements[1])
        self.data = self.data.append(s)


class MonitorCenter:
    def __init__(self):
        self.logcat = LogcatMonitor()

    def start(self):
        print('Start MonitorCenter')
        self.logcat.start()

    def stop(self):
        print('Stop MonitorCenter')
        self.logcat.stop()

    def retrieve_data(self):
        df_logcat = self.logcat.data

        d = {
            'Cam-0-sync': pd.Series([4.5, 5.5, 5.9], index=['1', '2', '3']),
            'Cam-0-async': pd.Series([11, 21.1, 23, 14], index=['1', '2', '3', '4']),
            'Cam-1-sync': pd.Series([4.4, 4.2, 6.3], index=['1', '2', '3']),
            'Cam-1-async': pd.Series([11, 12, 31, 14], index=['1', '2', '3', '4']),
        }

        df = pd.DataFrame(d)

        result = pd.concat([df_logcat, df], sort=False)
        return result
